<template>
  <view class="verify-container">
    <!-- 页面标题 -->
    <view class="header">
      <view class="verify-icon">🔐</view>
      <view class="title">输入验证码</view>
      <view class="subtitle">
        验证码已发送至 {{ formatPhone(phoneNumber) }}
      </view>
    </view>
    
    <!-- 验证码输入区域 -->
    <view class="verify-input-area">
      <view class="input-label">6位验证码</view>
      <view class="code-input-box">
        <input 
          v-for="(item, index) in codeArray" 
          :key="index"
          class="code-input"
          type="number"
          maxlength="1"
          :value="item"
          :focus="currentIndex === index"
          @input="onCodeInput($event, index)"
          @focus="onCodeFocus(index)"
        />
      </view>
      <view class="input-tips" :class="{ error: codeError }">
        {{ codeError || '请输入手机收到的6位验证码' }}
      </view>
    </view>
    
    <!-- 倒计时和重发 -->
    <view class="resend-area">
      <view class="countdown-text" v-if="countdown > 0">
        {{ countdown }}s后可重新发送
      </view>
      <button 
        class="resend-btn" 
        v-else
        @tap="resendCode"
        :disabled="resending"
      >
        {{ resending ? '发送中...' : '重新发送验证码' }}
      </button>
    </view>
    
    <!-- 用户信息展示 -->
    <view class="user-info" v-if="userInfo.nickName">
      <view class="avatar-area">
        <image :src="userInfo.avatarUrl" class="user-avatar" v-if="userInfo.avatarUrl" />
        <view class="default-avatar" v-else>👤</view>
      </view>
      <view class="user-details">
        <view class="user-name">{{ userInfo.nickName }}</view>
        <view class="phone-info">手机号：{{ formatPhone(phoneNumber) }}</view>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <view class="action-area">
      <button 
        class="submit-btn"
        :disabled="!isCodeComplete || submitting"
        @tap="submitCode"
      >
        {{ submitting ? '验证中...' : '确认验证' }}
      </button>
    </view>
    
    <!-- 认证状态 -->
    <view class="auth-status" v-if="authStatus">
      <view class="status-icon" :class="authStatus">
        {{ authStatus === 'success' ? '✅' : authStatus === 'failed' ? '❌' : '⏳' }}
      </view>
      <view class="status-text">{{ statusText }}</view>
    </view>
    
    <!-- 底部操作 -->
    <view class="footer">
      <button class="back-btn" @tap="goBack">返回修改手机号</button>
    </view>
  </view>
</template>

<script>
import { verifyCode, resendVerifyCode } from '@/api/wifi/auth'

export default {
  name: 'VerifyCode',
  data() {
    return {
      deviceId: '',
      sessionId: '',
      phoneNumber: '',
      userInfo: {},
      codeArray: ['', '', '', '', '', ''],
      currentIndex: 0,
      codeError: '',
      countdown: 60,
      countdownTimer: null,
      submitting: false,
      resending: false,
      authStatus: '', // success, failed, processing
      statusText: ''
    }
  },
  computed: {
    verifyCode() {
      return this.codeArray.join('')
    },
    
    isCodeComplete() {
      return this.verifyCode.length === 6 && /^\d{6}$/.test(this.verifyCode)
    }
  },
  onLoad(options) {
    console.log('Verify页面参数：', options)
    this.deviceId = options.deviceId || ''
    this.sessionId = options.sessionId || ''
    this.phoneNumber = options.phoneNumber || ''
    
    // 获取用户信息
    try {
      const userInfo = options.userInfo ? JSON.parse(decodeURIComponent(options.userInfo)) : {}
      this.userInfo = userInfo
    } catch (error) {
      console.error('解析用户信息失败：', error)
    }
    
    if (!this.deviceId || !this.sessionId || !this.phoneNumber) {
      uni.showToast({
        title: '参数错误',
        icon: 'error'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    
    // 开始倒计时
    this.startCountdown()
  },
  onUnload() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
  },
  methods: {
    // 格式化手机号显示
    formatPhone(phone) {
      if (!phone || phone.length !== 11) return phone
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    },
    
    // 验证码输入事件
    onCodeInput(e, index) {
      const value = e.detail.value
      if (value && !/^\d$/.test(value)) {
        return
      }
      
      this.codeArray[index] = value
      this.codeError = ''
      
      // 自动跳转到下一个输入框
      if (value && index < 5) {
        this.currentIndex = index + 1
      }
      
      // 如果输入完成，自动提交
      if (this.isCodeComplete) {
        setTimeout(() => {
          this.submitCode()
        }, 500)
      }
    },
    
    // 验证码输入框聚焦
    onCodeFocus(index) {
      this.currentIndex = index
    },
    
    // 开始倒计时
    startCountdown() {
      this.countdown = 60
      this.countdownTimer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          clearInterval(this.countdownTimer)
        }
      }, 1000)
    },
    
    // 重新发送验证码
    async resendCode() {
      if (this.resending) {
        return
      }
      
      try {
        this.resending = true
        
        const resendData = {
          sessionId: this.sessionId,
          deviceId: this.deviceId,
          phoneNumber: this.phoneNumber
        }
        
        console.log('重新发送验证码：', resendData)
        const response = await resendVerifyCode(resendData)
        
        if (response.code === 200) {
          uni.showToast({
            title: '验证码已重新发送',
            icon: 'success'
          })
          
          // 重新开始倒计时
          this.startCountdown()
          
          // 清空已输入的验证码
          this.codeArray = ['', '', '', '', '', '']
          this.currentIndex = 0
          this.codeError = ''
        } else {
          throw new Error(response.msg || '重新发送失败')
        }
      } catch (error) {
        console.error('重新发送验证码失败：', error)
        uni.showToast({
          title: error.message || '发送失败，请重试',
          icon: 'error'
        })
      } finally {
        this.resending = false
      }
    },
    
    // 提交验证码
    async submitCode() {
      if (!this.isCodeComplete) {
        this.codeError = '请输入完整的6位验证码'
        return
      }
      
      if (this.submitting) {
        return
      }
      
      try {
        this.submitting = true
        this.authStatus = 'processing'
        this.statusText = '正在验证码并开通网络...'
        
        const submitData = {
          sessionId: this.sessionId,
          deviceId: this.deviceId,
          phoneNumber: this.phoneNumber,
          verifyCode: this.verifyCode,
          userInfo: this.userInfo
        }
        
        console.log('提交验证码：', submitData)
        const response = await verifyCode(submitData)
        
        if (response.code === 200) {
          this.authStatus = 'success'
          this.statusText = '验证成功，网络已开通！'
          
          uni.showToast({
            title: '认证成功！',
            icon: 'success'
          })
          
          // 跳转到结果页面
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/wifi/result/index?result=success&deviceId=${this.deviceId}&sessionId=${this.sessionId}`
            })
          }, 1500)
        } else {
          throw new Error(response.msg || '验证码验证失败')
        }
      } catch (error) {
        console.error('提交验证码失败：', error)
        this.authStatus = 'failed'
        this.statusText = error.message || '验证失败，请重试'
        this.codeError = error.message || '验证码错误，请重新输入'
        
        // 清空验证码
        this.codeArray = ['', '', '', '', '', '']
        this.currentIndex = 0
        
        uni.showToast({
          title: error.message || '验证失败',
          icon: 'error'
        })
      } finally {
        this.submitting = false
        
        // 清除状态显示
        setTimeout(() => {
          if (this.authStatus !== 'success') {
            this.authStatus = ''
            this.statusText = ''
          }
        }, 3000)
      }
    },
    
    // 返回手机号页面
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.verify-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
  display: flex;
  flex-direction: column;
}

.header {
  text-align: center;
  color: #fff;
  margin-bottom: 80rpx;
}

.verify-icon {
  font-size: 120rpx;
  margin-bottom: 20rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
}

.subtitle {
  font-size: 28rpx;
  opacity: 0.9;
}

.verify-input-area {
  margin-bottom: 40rpx;
}

.input-label {
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  text-align: center;
}

.code-input-box {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  gap: 16rpx;
}

.code-input {
  width: 80rpx;
  height: 80rpx;
  background: #fff;
  border-radius: 16rpx;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  border: 4rpx solid transparent;
  
  &:focus {
    border-color: #1890ff;
  }
}

.input-tips {
  color: #fff;
  font-size: 24rpx;
  opacity: 0.8;
  text-align: center;
  
  &.error {
    color: #ff4757;
    opacity: 1;
  }
}

.resend-area {
  text-align: center;
  margin-bottom: 60rpx;
}

.countdown-text {
  color: #fff;
  font-size: 28rpx;
  opacity: 0.8;
}

.resend-btn {
  background: transparent;
  color: #fff;
  border: 2rpx solid rgba(255, 255, 255, 0.8);
  border-radius: 30rpx;
  padding: 16rpx 40rpx;
  font-size: 28rpx;
  
  &:disabled {
    opacity: 0.5;
  }
  
  &::after {
    border: none;
  }
}

.user-info {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 60rpx;
}

.avatar-area {
  margin-right: 30rpx;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  border: 3rpx solid #fff;
}

.default-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  background: #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  border: 3rpx solid #fff;
}

.user-details {
  flex: 1;
  color: #fff;
}

.user-name {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.phone-info {
  font-size: 24rpx;
  opacity: 0.8;
}

.action-area {
  margin-bottom: 40rpx;
}

.submit-btn {
  width: 100%;
  height: 100rpx;
  background: #fff;
  color: #667eea;
  border: none;
  border-radius: 50rpx;
  font-size: 32rpx;
  font-weight: bold;
  
  &:disabled {
    background: #ccc;
    color: #999;
  }
  
  &::after {
    border: none;
  }
}

.auth-status {
  text-align: center;
  margin-bottom: 40rpx;
}

.status-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
  
  &.processing {
    animation: rotate 1s linear infinite;
  }
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.status-text {
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
}

.footer {
  margin-top: auto;
  text-align: center;
}

.back-btn {
  width: 300rpx;
  height: 70rpx;
  background: transparent;
  color: #fff;
  border: 2rpx solid rgba(255, 255, 255, 0.5);
  border-radius: 35rpx;
  font-size: 28rpx;
  
  &::after {
    border: none;
  }
}
</style> 